package com.xxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxy.context.BaseContext;
import com.xxy.entity.Interaction;
import com.xxy.entity.Message;
import com.xxy.entity.User;
import com.xxy.entity.dto.InteractionQueryDTO;
import com.xxy.entity.dto.ProductQueryDTO;
import com.xxy.entity.dto.QueryDTO;
import com.xxy.entity.dto.UserQueryDTO;
import com.xxy.entity.vo.ProductVO;
import com.xxy.enums.InteractionEnum;
import com.xxy.mapper.InteractionMapper;
import com.xxy.mapper.MessageMapper;
import com.xxy.mapper.ProductMapper;
import com.xxy.mapper.UserMapper;
import com.xxy.result.PageResult;
import com.xxy.result.Result;
import com.xxy.service.IInteractionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class InteractionServiceImpl extends ServiceImpl<InteractionMapper, Interaction> implements IInteractionService {
    @Autowired
    private InteractionMapper interactionMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public List<Interaction> queryByFilter(InteractionQueryDTO interactionQueryDTO) {
        LambdaQueryWrapper<Interaction> queryWrapper = new LambdaQueryWrapper<>();
        if (interactionQueryDTO.getProductId()!=null) {
            queryWrapper.eq(Interaction::getProductId,interactionQueryDTO.getProductId());
        }
        if (interactionQueryDTO.getType()!=null) {
            queryWrapper.eq(Interaction::getType,interactionQueryDTO.getType());
        }
        if (interactionQueryDTO.getUserId()!=null) {
            queryWrapper.eq(Interaction::getUserId,interactionQueryDTO.getUserId());
        }
        return interactionMapper.selectList(queryWrapper);
    }

    @Override
    public Result<List<ProductVO>> queryCollection() {
        //查询该用户类型为收藏的交互记录
        LambdaQueryWrapper<Interaction> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Interaction::getUserId,BaseContext.getCurrentId())
                .eq(Interaction::getType,InteractionEnum.SAVE.getType());
        List<Interaction> interactionList = interactionMapper.selectList(queryWrapper);
        List<Long> productIds =
                interactionList.stream().map(Interaction::getProductId).collect(Collectors.toList());
        //通过商品id列表查询返回商品集合
        if (productIds.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        List<ProductVO> productVOS = productMapper.queryProductVoList(productIds);
        return Result.success(productVOS);
    }

    @Override
    public void view(Long productId) {
        //查询该用户类型为浏览的交互记录
        LambdaQueryWrapper<Interaction> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Interaction::getUserId,BaseContext.getCurrentId())
                .eq(Interaction::getType,InteractionEnum.VIEW.getType())
                .eq(Interaction::getProductId,productId);
        List<Interaction> interactionList = interactionMapper.selectList(queryWrapper);
//        log.info("查询到该用户类型为浏览的交互记录：{}",interactionList);
        if (interactionList.isEmpty()) {
            Interaction interaction = Interaction.builder()
                    .userId(BaseContext.getCurrentId())
                    .productId(productId)
                    .type(InteractionEnum.VIEW.getType())
                    .createTime(LocalDateTime.now())
                    .build();
            interactionMapper.insert(interaction);
        }
    }

    @Override
    public List<ProductVO> queryView() {
        //查询该用户类型为浏览的交互记录
        LambdaQueryWrapper<Interaction> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Interaction::getUserId,BaseContext.getCurrentId())
                .eq(Interaction::getType,InteractionEnum.VIEW.getType());
        List<Interaction> interactionList = interactionMapper.selectList(queryWrapper);
        List<Long> productIds =
                interactionList.stream().map(Interaction::getProductId).collect(Collectors.toList());
        //通过商品id列表查询返回商品集合
        if (productIds.isEmpty()) {
            return Collections.emptyList();
        }
        return productMapper.queryProductVoList(productIds);
    }

    @Override
    public void saveOperation(Long productId) {
        InteractionQueryDTO interactionQueryDTO=new InteractionQueryDTO();
        interactionQueryDTO.setUserId(BaseContext.getCurrentId());
        interactionQueryDTO.setProductId(productId);
        interactionQueryDTO.setType(InteractionEnum.SAVE.getType());
        List<Interaction> interactionList = this.queryByFilter(interactionQueryDTO);
        //收藏
        if (interactionList.isEmpty()) {
            Interaction interaction=Interaction.builder()
                    .userId(BaseContext.getCurrentId())
                    .productId(productId)
                    .type(InteractionEnum.SAVE.getType())
                    .createTime(LocalDateTime.now())
                    .build();
            interactionMapper.insert(interaction);
        }else {
            //取消收藏
            Interaction interaction = interactionList.get(0);
            interactionMapper.deleteById(interaction.getId());
        }
    }

    @Override
    public Result<String> wantProduct(Long productId) {
        //查询用户是否已点击我想要
        InteractionQueryDTO interactionQueryDTO =
                createInteractionQueryDTO(BaseContext.getCurrentId(), productId, InteractionEnum.WANT.getType());
        List<Interaction> interactionList = this.queryByFilter(interactionQueryDTO);
        if (! interactionList.isEmpty()) {
            return Result.success("你已经将此商品标记为我想要");
        }

        ProductQueryDTO productQueryDTO=new ProductQueryDTO();
        productQueryDTO.setId(productId);
        List<ProductVO> productVOS = productMapper.queryByFilter(productQueryDTO);
        if (productVOS.isEmpty()) {
            return Result.success("商品不存在");
        }

        ProductVO productVO = productVOS.get(0);
        if (productVO.getUserId().equals(BaseContext.getCurrentId())) {
            return Result.success("不能想要自己商品");
        }
        //查询用户名称
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,BaseContext.getCurrentId());
        User user = userMapper.selectOne(queryWrapper);
        //新增消息记录设置为未读
        Message message = Message.builder()
                .userId(productVO.getUserId())
                .isRead(0)
                .createTime(LocalDateTime.now())
                .content("用户【"+user.getNickname()+"】对你的商品【"+productVO.getName()+"】感兴趣")
                .build();
        messageMapper.insert(message);
        //保存交互记录
        interactionMapper.insert(Interaction.builder()
                .userId(BaseContext.getCurrentId())
                .productId(productId)
                .type(InteractionEnum.WANT.getType())
                .createTime(LocalDateTime.now())
                .build());
        return Result.success("谢谢你的对商品的喜爱");
    }

    public InteractionQueryDTO createInteractionQueryDTO(Long userId,Long productId, Integer type) {
        InteractionQueryDTO interactionQueryDTO=new InteractionQueryDTO();
        interactionQueryDTO.setUserId(userId);
        interactionQueryDTO.setProductId(productId);
        interactionQueryDTO.setType(type);
        return interactionQueryDTO;
    }
}
